import triangle
from stl import mesh#pip intsall pumpy-stl
import numpy as np
# 定义外边界的顶点
vertices = [
    (0, 0), (1, 0), (1, 1), (0, 1)
]

# 定义外边界的线段
segments = [
    (0, 1), (1, 2), (2, 3), (3, 0)
]

# 定义内洞的顶点（假设洞是一个小正方形，位于大正方形的中间）
hole_vertices = [
    (0.25, 0.25), (0.75, 0.25), (0.75, 0.75), (0.25, 0.75)
]

# 定义内洞的线段
hole_segments = [
    (4, 5), (5, 6), (6, 7), (7, 4)
]

# 将洞的顶点添加到外边界的顶点列表中
vertices += hole_vertices

# 创建 tridict
tridict = {
    'vertices': vertices,
    'segments': segments + hole_segments,
    'holes': [(0.5, 0.5)]  # 洞的中心点坐标
}

# 使用 'p' 参数进行三角划分
tri = triangle.triangulate(tridict, 'p')

# 输出三角划分的结果
print(tri['vertices'])  # 三角划分后的顶点
print(tri['triangles'])  # 三角划分后的三角形
triangles = tri['triangles']
vertices=tri['vertices']


faces_array = np.array(triangles) 
vertices_array = np.array([(0,x, y) for x, y in vertices])
triangle_mesh = mesh.Mesh(np.zeros(faces_array.shape[0], dtype=mesh.Mesh.dtype))
for i, fa in enumerate(faces_array):
        for j in range(3):
            triangle_mesh.vectors[i][j] = vertices_array[fa[j], :]
triangle_mesh.save('merged_output_mesh.stl')

